<template>
  <div>
    <a-form
      ref="FormRef"
      :model="FormState"
      :rules="FormRule"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
    >
      <a-form-item label="广告分类" has-feedback required name="cate_id">
        <a-select v-model:value="FormState.cate_id" placeholder="请选择分类">
          <a-select-option
            v-for="d in allCate"
            :key="d.id"
            :value="d.id"
            :disabled="parseInt(FormState.id) == d.id"
          >
            {{ d.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="标题" has-feedback required name="title">
        <a-input v-model:value="FormState.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="广告图" has-feedback>
        <a-upload
          name="file"
          listType="picture-card"
          class="avatar-uploader"
          :showUploadList="false"
          :action="apiUrl + 'api/common/uploadFile'"
          :headers="uploadHeaders"
          :beforeUpload="beforeUpload"
          @change="uploadChange"
        >
          <img v-if="FormState.pic" :src="FormState.pic" alt="广告图" />
          <div v-else>
            <loading-outlined v-if="uploadLoading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-input v-model:value="FormState.pic" name="pic"/>
      </a-form-item>
      <a-form-item label="广告链接" has-feedback required name="url">
        <a-input v-model:value="FormState.url" placeholder="请输入链接" />
      </a-form-item>
      <a-form-item label="开始展示时间" has-feedback required name="start_time">
        <a-date-picker
          v-model:value="start_time"
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择时间"
          class="width100"
          @change="changeStartDate"
        />
      </a-form-item>
      <a-form-item label="结束展示时间" has-feedback required name="end_time">
        <a-date-picker
          v-model:value="end_time"
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择时间"
          class="width100"
          @change="changeEndDate"
        />
      </a-form-item>
      <a-form-item label="排序" has-feedback required name="sort">
        <a-input-number
          v-model:value="FormState.sort"
          placeholder="请输入序号，大的靠前"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="状态" has-feedback required name="status">
        <a-radio-group v-model:value="FormState.status" name="status">
          <a-radio :key="1" :value="1">正常</a-radio>
          <a-radio :key="-1" :value="-1">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item style="margin-left: 12.5%">
        <a-button type="primary" html-type="submit" :loading="ConfirmLoading" @click="OnSubmit">
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
/* eslint-disable */
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import { Row, Col, Upload, DatePicker, InputNumber } from 'ant-design-vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { getItemInfo, editItemInfo, getCateWithLevel } from '@/api/ads'
import { useRouter } from 'vue-router'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { storage } from '@/utils/Storage'
import { apiUrl, getRangeDate } from '@/utils/common'
import dayjs, { Dayjs } from 'dayjs'

export default defineComponent({
  name: 'ItemEdit',
  components: {
    PlusOutlined,
    LoadingOutlined,
    [Row.name]: Row,
    [Upload.name]: Upload,
    [DatePicker.name]: DatePicker,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col
  },
  setup() {
    const FormRef = ref()
    const router = useRouter()
    const dateFormat = 'YYYY/MM/DD HH:mm:ss'
    const todayDate = getRangeDate(1, 'one')
    console.log(todayDate)
    const state = reactive({
      ConfirmLoading: false,
      uploadHeaders: {},
      uploadLoading: false,
      apiUrl: apiUrl(),
      // eslint-disable-next-line
      start_time: ref<Dayjs>(),
      // eslint-disable-next-line
      end_time: ref<Dayjs>(),
      allCate: [],
      editorData: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    })
    const FormState = reactive({
      cate_id: '',
      title: '',
      id: router.currentRoute.value.query.id != undefined ? router.currentRoute.value.query.id : '',
      pic: '',
      status: '',
      url: '',
      start_time: '',
      end_time: '',
      sort: 0
    })
    const FormRule = {
      cate_id: [
        { required: true, message: '请选择分类', trigger: ['blur', 'change'], type: 'number' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: ['blur', 'change'], type: 'number' }
      ],
      pic: [{ required: true, message: '请上传广告图', trigger: ['blur', 'change'] }],
      end_time: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }],
      start_time: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }],
      sort: [
        { required: true, message: '请输入序号', trigger: ['blur', 'change'], type: 'number' }
      ],
      url: [
        { required: true, message: '请输入链接', trigger: ['blur', 'change'], type: 'string' }
      ],
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }]
    }
    onMounted(() => {
      getCateList()
      getDataInfo()
    })

    const changeStartDate = (e, value) => {
      FormState.start_time = value
    }
    const changeEndDate = (e, value) => {
      FormState.end_time = value
    }

    function getDataInfo() {
      getItemInfo({ id: FormState.id }).then((res) => {
        for (let item in res) {
          FormState[item] = res[item]
          if (item == 'start_time' || item == 'end_time') {
            state[item] = dayjs(res[item], dateFormat)
          }
        }
      })
    }
    const getCateList = () => {
      getCateWithLevel({}).then((res) => {
        state.allCate = res
      })
    }
    const OnSubmit = () => {
      FormRef.value
        .validate()
        .then(() => {
          editItemInfo(toRaw(FormState))
            .then((res) => {
              if (res.code === 200) {
                router.go(-1)
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.ConfirmLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    function uploadChange(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        FormState.pic = info.file.response.data[0]
        state.uploadLoading = false
      }
    }
    function beforeUpload(file) {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        requestFailed(null, '仅可上传JPG、PNG格式的文件')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        requestFailed(null, '上传图片需小于2MB')
      }
      return isJPG && isLt2M
    }
    return {
      ...toRefs(state),
      FormRef,
      beforeUpload,
      changeStartDate,
      changeEndDate,
      uploadChange,
      getCateList,
      FormState,
      FormRule,
      OnSubmit,
      getDataInfo
    }
  }
})
</script>

<style scoped></style>
